# -*- coding: utf-8 -*-
#
#	Copyright (C) - 2011	Alexander Ayasca Esquives 
#				            <alexander.uni.fiis@gmail.com>

#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.

#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.

#	You should have received a copy of the GNU General Public License
#	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

################################################################################
# META
################################################################################

__version__ =	"0.1"
__license__ =	"GPL 3"
__author__ =	"Alexander Ayasca Esquives"
__date__ =		"2011-04-03"

########################################################################
# IMPORTS
########################################################################

from PyQt4.QtCore import Qt,SIGNAL
from PyQt4.QtGui import QGraphicsGridLayout,QGraphicsLinearLayout,QHBoxLayout,QLineEdit,QLayoutItem,QApplication,QGraphicsWidget
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript

from validate_url import validate_url
import urllib2, simplejson


class GoogleURLShortener(plasmascript.Applet):
	def __init__(self,parent,args=None):
		plasmascript.Applet.__init__(self,parent)
	
	def init(self):
		self.setHasConfigurationInterface(False)
		self.resize(280, 80)
		self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
		self.setLayout(QGraphicsGridLayout())
		
		self.layout1 = QGraphicsLinearLayout()
		# linea-de-edicion
		self.lineedit = Plasma.LineEdit()
		self.lineedit.resize(180,60)

		# botón
		self.pushbutton = Plasma.PushButton()
		self.pushbutton.setText("Acortar")
		self.pushbutton.resize(100,60)
		
		# atribución
		self.credits_label = Plasma.Label()
		self.credits_label.nativeWidget().setOpenExternalLinks(True)
		self.credits_label.setAlignment(Qt.AlignRight)
		
		#nada
		self.nada=Plasma.Label()
		self.nada.setText('')
		
		logo = u"%scontents/images/google-attribution.png" % self.applet.package().path()
		
		self.credits_label.setText("<a href=\"http://goo.gl//\"><img src=\"%s\"></a>" % logo)
		
		# agregamos los items
		self.layout1.addItem(self.lineedit)
		self.layout1.addItem(self.pushbutton)
		
		self.layout().addItem(self.layout1, 0, 0)
		self.layout().addItem(self.nada, 0, 1)
		self.layout().addItem(self.nada, 1, 1)
		self.layout().addItem(self.credits_label, 2, 0)

		#conexion
		self.connect(self.pushbutton, SIGNAL("clicked()"), self.acorta)

	def acorta(self):
		url = unicode(self.lineedit.text())
		base=validate_url(url)
		
		GOOGL_URL = 'https://www.googleapis.com/urlshortener/v1/url'
		APIKEY = 'AIzaSyBs1vgXLG5D4xerUuEKP3BSCHPJv1eNBUw'
		
		parametros = simplejson.dumps({"longUrl":base})
		completa = GOOGL_URL + '?key=' + APIKEY
		cabecera = {'Content-Type' : 'application/json'}
		
		try:
			pedido = urllib2.Request(completa, parametros, cabecera)
			resp = simplejson.load(urllib2.urlopen(pedido))
			
			# copiamos el link corto generado al portapapeles.
			
			clipboard = QApplication.clipboard()
			clipboard.setText(resp["id"])
			
			# tambien, mostramos la url
			self.lineedit.setText(resp["id"])
			
		except Exception, error:
			print "Error: %s" % error
			print "No se pudo recortar la URL"

def CreateApplet(parent):
    return GoogleURLShortener(parent)
